/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package objectRank;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.fiu.cis.personalize.shared.GoogleDocument;

/**
 *
 * @author Reza
 */
public class ProcessServlet extends HttpServlet {

    

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ClassNotFoundException {
        response.setContentType("text/html;charset=UTF-8");
        GraphBean gb = new GraphBean();
        String query = request.getParameter("query");
        File file = new File("C:\\Users\\Reza\\Documents\\NetBeansProjects\\MyGroups"
                            + "\\src\\java\\objectRank\\tempDoc.bin");
        ObjectInputStream objectIn = null;
        String output;
        try{
            objectIn = new ObjectInputStream(new BufferedInputStream(
                       new FileInputStream(file)));
            LinkedList<GoogleDocument> googleDocuments = (LinkedList<GoogleDocument>) objectIn.readObject();
            gb.googleDocuments = googleDocuments;
        }catch(ClassNotFoundException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }catch(IOException e){
            System.err.println("Error in reading file: " + e);
        }

        try {
            objectIn.close(); // Close the input stream
        }catch(IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
        gb.calculateRank(query);
        gb.integrateWithGoogle();

        Iterator<GoogleDocument> itr = gb.googleDocuments.iterator();
        GoogleDocument tempDoc;
        while(itr.hasNext()){
            tempDoc = itr.next();
            Node n = gb.queryGraph.addNode(">>document>> ".concat(tempDoc.getURL()));
            ((Document)n).setTitle(tempDoc.getTitle());
            //((Document)n).setContent(tempDoc.getContent());
        }
        output = gb.showOutput();

        try {
            gb.file1.delete(); // Delete the file to write the updated QueryObject again
            //gb.file1.createNewFile();
            gb.objectOut = new ObjectOutputStream(new BufferedOutputStream(
                        new FileOutputStream(gb.file1)));
            gb.objectOut.writeObject(gb.queryGraph);
            gb.objectOut.close(); // Close the output stream
        }catch(IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
        
        PrintWriter out = response.getWriter();

        try {
            out.println(output);

//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet QueryServlet</title>");
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet QueryServlet at " + output + "</h1>");
//            out.println("</body>");
//            out.println("</html>");

        } finally {
            out.flush();
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
